﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using PetaPoco;
using PmSoft;
using PmSoft.ApplicationContext;
using PmSoft.Caching;
using PmSoft.DBContext;
using PmSoft.Repositories;

namespace Modules.System.Flow
{
    [UseDI(ServiceLifetime.Scoped)]
    public class SysFlowEngineRepository : Repository<SysFlowEngine, DefaultDbContext>
    {
        private readonly ILogger logger;

        public SysFlowEngineRepository(DefaultDbContext dbContext, IApplicationContext applicationContext, ILogger<SysFlowEngineRepository> logger)
            : base(dbContext, applicationContext)
        {
            this.logger = logger;
        }

        public IEnumerable<SysFlowEngine> GetSysFlowEngineByFlowId(int flowId)
        {
            int areaVersion = EntityCacheService.GetAreaVersion("FlowId", flowId);
            return GetTopEntities(1000, CachingExpirationType.ObjectCollection, () =>
            {
                return $"SysFlowEngineByFlowId:{flowId}:{areaVersion}";
            }, () =>
            {
                Sql sql = Sql.Builder
                .Select("id")
                .From("sys_flow_engine")
                .Where("flow_id=@0", flowId)
                .OrderBy("sort");
                return sql;
            });
        }

        public IEnumerable<SysFlowEngine> GetFlowEnginesByFlowIds(IEnumerable<int> flowIds)
        {
            Sql sql = Sql.Builder;
            sql.Select("id")
                .From("sys_flow_engine");
            sql.Where("flow_id in(@0)", flowIds);
            var ids = DbContext.FetchFirstColumn<int>(sql);
            return PopulateEntitiesByEntityIds(ids);
        }
    }
}